package com.homework.api_code.controller;

import com.homework.interface_code.services.CodeService;
import com.homework.interface_email.services.EmailService;
import com.homework.util.ResultMsg;
import com.homework.util.ResultUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController()
@RequestMapping("/api/code")
public class CodeController {

    @Reference
    protected CodeService codeService;

    @Reference(timeout = 10000) //超时设置  不然会产生超时
    protected EmailService emailService;

    /**
     * 创建验证码，保存到数据库中， 同时调用邮件服务发送邮件
     * @param email
     * @return
     */
    @RequestMapping("/create/{email}")
    public ResultMsg code(@PathVariable("email") String email) {
        String code =  codeService.generateCode();
        boolean bool = codeService.saveCode(email, code);
        if(bool) {
            //todo 调用邮件服务发送邮件
            //emailFeignClient.send(email, code);
            bool = emailService.send(email, code);
        }

        if(bool) {
            return ResultUtil.success();
        }

        return ResultUtil.error(100, "验证码生成失败");
    }

    @RequestMapping("/validate/{email}/{code}")
    public ResultMsg validate(@PathVariable("email") String email, @PathVariable("code") String code) {
        ResultMsg msg = null;
        try {
            msg = codeService.validate(email, code);
        } catch (Exception e) {

        }

        return msg;
    }
}
